import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/ball_pulse_footer.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/custom/judje_dialog.dart';
import 'package:flutter_juwo/ui/model/base_entity.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';

import 'model/task_list_entity.dart';
import 'noData.dart';

class OrderAll extends StatefulWidget {
  int index;

  OrderAll({int index = 0}) {
    this.index = index;
  }

  @override
  _OrderAllState createState() => _OrderAllState();
}

class _OrderAllState extends State<OrderAll> {
  MyPageState ps = MyPageState.LOADING;
  EasyRefreshController _easyRefreshController = EasyRefreshController();
  TaskListEntity _entity = null;

  ///当前码
  int _currentPage = 1;

  ///页数默认为1 通过 总数 计算得来
  int _pages = 1;

  ///一页 20 条数据
  int _itemNum = 20;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getData();
  }

  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
    if (mounted) {
      this.getData();
    }

    print("deactivate-------------------");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.c243,
      body: getContent(),
    );
  }

  getContent() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.NOT_DATA) {
      return NoData();
    }

    if (ps == MyPageState.HAVE_DATA) {
      return EasyRefresh.custom(
        controller: _easyRefreshController,

        /// firstRefresh: true,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        header: BallPulseHeader(),
        footer: BallPulseFooter(),
        onRefresh: () async {
          await Future.delayed(Duration(seconds: 1), () {
            _currentPage = 1;
            this.getData(page: _currentPage);
          });
        },
        onLoad: () async {
          await Future.delayed(Duration(seconds: 1), () {
            if (_currentPage < _pages) {
              _currentPage++;
              this.getData(page: _currentPage);
            } else {
              _easyRefreshController.finishLoad();
              // ToastUtil.showShortToast("没有更多了");
            }
          });
        },
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return this.getItem(_entity.data.result[index]);
              },
              childCount: _entity.data.result.length,
            ),
          ),
        ],
      );
    }

    return NoData();
  }

  ///没有数据
  void noData() {
    ps = MyPageState.NOT_DATA;
    setState(() {});
  }

  ///有数据
  void haveData() {
    ps = MyPageState.HAVE_DATA;
    setState(() {});
  }

  Future getData({int page = 1}) async {
    FormData params = FormData.from({"status": getStatus(), "page": page});
    DioManager.getInstance().get(Api.TASK_GETMYLIST, params, (json) {
      TaskListEntity data = TaskListEntity.fromJson(json);

      ///第一次加载
      if (page == 1) {
        if (null == data) {
          this.noData();
          return;
        }
        if (data.code != 200) {
          this.noData();
          return;
        }
        if (null == data.data.result || data.data.result.length <= 0) {
          this.noData();
          return;
        }
        _entity = data;
        _pages = data.data.totalPage;
        this.haveData();
        _easyRefreshController.finishRefresh();
        return;
      }

      ///上拉加载
      if (null != data &&
          data.data.result != null &&
          data.data.result.length > 0) {
        _entity.data.result.addAll(data.data.result);
        setState(() {});
        _easyRefreshController.finishLoad();
        return;
      }

      /// ToastUtil.showShortToast("没有更多了");
      return;
    }, (errMsg) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      NavigatorUtils.goBack(context);
    });
  }

  getStatus() {
    if (widget.index == 1) {
      return "A";
    } else if (widget.index == 2) {
      return "B";
    } else if (widget.index == 3) {
      return "C";
    } else if (widget.index == 4) {
      return "D";
    }
    return "";
  }

  getItem(TaskListDataResult result) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(10)),
      padding: EdgeInsets.all(ScreenUtil().setWidth(20)),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6),
      ),
      child: Column(
        children: <Widget>[
          getRow1(result.timeOrder, result.statusCn),
          getRow2(result),
          getRow3(),
          getRow4(result),
        ],
      ),
    );
  }

  getRow1(String timeOrder, String statusCn) {
    return Container(
      child: Row(
        children: <Widget>[
          Container(
            child: Text(
              "接单时间:",
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangRegular),
            ),
          ),
          Container(
            child: Text(
              "$timeOrder",
              style: TextStyles.custom(
                  28, Colours.appC3, Font.PingFangMedium),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              alignment: Alignment.centerRight,
              child: Text(
                "$statusCn",
                style: TextStyles.custom(
                    28, Colours.appC10, Font.PingFangMedium),
              ),
            ),
          )
        ],
      ),
    );
  }

  getRow2(TaskListDataResult result) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(0),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(0),
          ScreenUtil().setWidth(0)),
      child: Row(
        children: <Widget>[
          Container(
            child: UiUtils.cachedNetworkImage(120, 120, result.exampic),
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    child: Row(
                      children: <Widget>[
                        Container(
                          child: UiUtils.cachedNetworkImage(36, 36, result.pic),
                        ),
                        Container(
                          margin:
                              EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                          child: Text(
                            getName(result.storeName),
                            style: TextStyles.custom(28, Colours.appC2,
                                Font.PingFangMedium),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            alignment: Alignment.centerRight,
                            child: Text(
                              "账号：${result.account}",
                              style: TextStyles.custom(26, Colours.appC1,
                                  Font.PingFangMedium),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
                    child: Text(
                      "编号：${result.code}",
                      style: TextStyles.custom(
                          26, Colours.appC3, Font.PingFangMedium),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: Text(
                              getGold(result.price, result.goldstatus,
                                  result.status),
                              style: TextStyles.custom(28, Colours.appC10,
                                  Font.PingFangMedium),
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: Text(
                              getMoeny(result.money, result.moneystatus,
                                  result.status),
                              style: TextStyles.custom(28, Colours.appC3,
                                  Font.PingFangMedium),
                            ),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  String getName(String storeName) {
    List<String> list = storeName.split("");
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < list.length; i++) {
      if ((i + 1) % 2 == 1) {
        sb.write(list[i]);
        if (i != list.length - 1) {
          sb.write("*");
        }
      }
    }
    return sb.toString();
  }

  getRow3() {
    return Container(
      margin: EdgeInsets.only(
          bottom: ScreenUtil().setWidth(20), top: ScreenUtil().setWidth(30)),
      child: UiUtils.divider(height: 2),
    );
  }

  getRow4(TaskListDataResult result) {
    List<Widget> list = [];
    list.add(Expanded(
      flex: 1,
      child: Container(
        alignment: Alignment.centerLeft,
        child: Text(
          "${result.memo}/共${result.totalStep}步",
          style: TextStyles.custom(
              28, Colours.appC3, Font.PingFangMedium),
        ),
      ),
    ));

    if (result.status == "1" || result.status == "2") {
      ///显示 取消任务，继续任务
      list.add(getBtnItem("取消任务", result.billId, result.id));
      list.add(getBtnItem("继续任务", result.billId, result.id));
    }

    if (result.status == "4") {
      ///显示取消任务
      list.add(getBtnItem("继续任务", result.billId, result.id));
    }

    return Row(
      children: list,
    );
  }

  Widget getBtnItem(String s, String id, int itemId) {
    return InkWell(
      onTap: () {
        if (s == "取消任务") {
          UiUtils.showMyDialog(context, text: "正在取消");
          showDeleteDialog(id);

          return;
        }
        if (s == "继续任务") {
          //   NavigatorUtils.push(context, "${Routes.taskStep}?id=${14754}"); //测试
           NavigatorUtils.push(context, "${Routes.taskStep}?id=${itemId}");//线上

          return;
        }
      },
      child: Container(
        margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(10), 0, ScreenUtil().setWidth(10), 0),
        decoration: BoxDecoration(
            border: Border.all(
                color: s == "取消任务" ? Colours.appC3 : Colours.appC16,
                width: ScreenUtil().setWidth(1))),
        child: Text(
          "$s",
          style: TextStyles.custom(
              30,
              s == "取消任务" ? Colours.appC3 : Colours.appC16,
              Font.PingFangMedium),
        ),
      ),
    );
  }

  void showDeleteDialog(String id) {
    showElasticDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return JudjeDialog(
            title: "确定取消任务",
            value: "任务取消后可以再接!",
            onPressed: () {
              Navigator.pop(context);
              canceltask(id);
            },
          );
        });
  }

  void canceltask(String id) {
    FormData formData = FormData.from({"id": id});
    DioManager.getInstance().post(Api.TASK_CANCELTASK, formData, (json) {
      BaseEntity entity = BaseEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }
      if (entity.code != 200) {
        ToastUtil.showShortErrToast(entity.message);
        _easyRefreshController.callRefresh();
        NavigatorUtils.goBack(context);
        return;
      }
      NavigatorUtils.goBack(context);
      _easyRefreshController.callRefresh();
    }, (err) {
      _easyRefreshController.callRefresh();
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      NavigatorUtils.goBack(context);
    });
  }

  String getGold(String price, String goldstatus, String status) {
    if (status == "10" || status == "9") {
      return "$price金";
    } else {
      return "$price金($goldstatus)";
    }
  }

  String getMoeny(String price, String moenyStatus, String status) {
    if (status == "10" || status == "9") {
      return "$price元";
    } else {
      return "$price元($moenyStatus)";
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _easyRefreshController.dispose();
  }
}
